import Mock from 'mockjs';

function param2Obj(url: string) {
	const search = url.split('?')[1];
	if (!search) {
		return {};
	}
	return JSON.parse(
		'{"' +
			decodeURIComponent(search)
				.replace(/"/g, '\\"')
				.replace(/&/g, '","')
				.replace(/=/g, '":"')
				.replace(/\+/g, ' ') +
			'"}'
	);
}

const mockList: Array<{ rurl: string | RegExp; rtype: string; response: any }> = [
	{
		rurl: '/login',
		rtype: 'post',
		response: (config: any) => {
			const { username, password } = JSON.parse(config.body);

			if (username === 'admin' && password === 'admin2020') {
				const data = {
					username: 'admin',
					token: Mock.mock('@guid'),
					roles: [ 'admin' ]
				};

				return {
					code: 0,
					data,
					msg: ''
				};
			} else {
				return {
					code: 1,
					data: null,
					msg: '用户名不存在或用户登录密码错误.'
				};
			}
		}
	},
	{
		rurl: RegExp('refreshToken.*'),
		rtype: 'get',
		response: (config: any) => {
			const { token } = param2Obj(config.url);

			if (token.length > 0) {
				const data = {
					username: 'admin',
					token: Mock.mock('@guid'),
					roles: [ 'admin' ]
				};
	
				return {
					code: 0,
					data,
					msg: ''
				};
			}
		}
	}
];

(function() {
	for (const i of mockList) {
		Mock.mock(i.rurl, i.rtype, i.response);
	}
})();
